package FenxiaoService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/tools/mylog"

	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
)

// HandleOrderConfirm 处理订单 确认收货
func HandleOrderConfirm(orderId int) {
	ctx := context.Background()
	var fodList []*entity.FenxiaoOrderDetails
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_order_details").Where(
		"status > 0 AND order_id = ?", orderId).Scan(&fodList)
	if err != nil {
		mylog.ErrorLog("HandleOrderConfirm 错误：", err.Error())
		return
	}
	if fodList == nil {
		mylog.ErrorLog("HandleOrderConfirm 错误：fodList 为空")
		return
	}
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		_, err := tx.Model("fenxiao_order").Unscoped().Where(
			"status > 0 AND order_id = ?", orderId).Update(g.Map{
			"status": 99,
		})
		if err != nil {
			return err
		}
		_, err = tx.Model("fenxiao_order_details").Unscoped().Where(
			"status > 0 AND order_id = ?", orderId).Update(g.Map{
			"status": 99,
		})
		if err != nil {
			return err
		}

		// 写入流水，收入
		for _, item := range fodList {
			err = InvoiceChange(tx, 1, item.FenxiaoUserId, item.MemberId,
				int(item.Paid*int64(item.Rate)/100000), item.Id, "fenxiao_order_details")
			if err != nil {
				return err
			}
		}

		return nil
	})
	if err != nil {
		return
	}
}
